package com.blt.govdata.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.blt.govdata.controller.base.BaseController;
import com.blt.govdata.model.TProject;
import com.blt.govdata.service.ICommonService;
import com.blt.govdata.utils.CommonUtil;
import com.blt.govdata.utils.ExcelUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/common")
public class CommonController extends BaseController {
    @Autowired
    ICommonService service;
    @GetMapping(value = "/exportExcelBySQL")

    public void exportExcelBySQL(@RequestParam(defaultValue = "SELECT '无' AS '数据' FROM DUAL") String sql) {
        sql = sql.toLowerCase();
        if(StringUtils.containsAny(sql,"delete","update","truncate")) {
            System.out.println("不支持此类操作");
            return;
        }
        EntityWrapper ew= new EntityWrapper();
        ew.setEntity(TProject.class);
        List<String> colunms = Lists.newArrayList();//列名
        List<Map<String,Object>> result = this.service.selectBySQL(sql);
        List<Object[]> contentList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(result)) {
            Map<String,Object> map = result.get(0);
            for(String key:map.keySet()){
                colunms.add(key);
            }
            for (Map<String,Object> row:result) {
                List<Object> values = new ArrayList<>();
                for (String key:row.keySet()){
                    values.add(row.get(key));
                }
                Object[] o = new Object[row.size()];
                values.toArray(o);
                contentList.add(o);
            }
            String[] headArray = new String[colunms.size()];
            colunms.toArray(headArray);
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_hhMMss");
                String dateString = String.valueOf(sdf.format(new Date()));
                ExcelUtil.ExportExcel(response, headArray, contentList, "export_"+dateString+".xls");
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }else{
            return;
        }
    }

}
